using System;
using System.Threading;
using System.Reflection;
using Servlets.Api;
using System.Text.RegularExpressions;
using System.Web;
using System.Linq;

namespace Servlets.Server
{
	class ServletInvoker
	{
		private Object instance;
		private MethodInfo method;
		private object[] parameters;
		
		public ServletInvoker(Object instance, MethodInfo method, params string[] parameters) {
			this.instance = instance;
			this.method = method;
			this.parameters = parameters.Select(p => HttpUtility.UrlDecode(p)).ToArray();
		}
		
		public void Invoke(IRequest request, IResponse response) {
			object[] finalParameters = MergeArrays(new object[]{request, response}, parameters);
			
			var methodParams = method.GetParameters();
			for(int i = 2; i < methodParams.Length; i++) {
				var p = methodParams[i];
				Type type = p.ParameterType;
				convertType(finalParameters, i, type);
			}
			method.Invoke(instance, finalParameters);
		}
		
		private void convertType(object[] finalParameters, int i, Type type) {
			String p = finalParameters[i].ToString();
			MethodInfo method = type.GetMethod("Parse", new Type[] {typeof(string)});
			finalParameters[i] = method.Invoke(null, new object[] {p});
		}
		
		private object[] MergeArrays(object[] array1, object[] array2) {
			object[] rtn = new object[array1.Length + array2.Length];
			int count = 0;
			foreach(var v in array1) {
				rtn[count++] = v;
			}
			foreach(var v in array2) {
				rtn[count++] = v;
			}
			
			return rtn;
		}
	}
}

